package com.example.stripe_connection_plugin;


import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanAndConnectCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stripe.stripeterminal.Terminal;
import com.stripe.stripeterminal.external.callable.BluetoothReaderListener;
import com.stripe.stripeterminal.external.callable.Callback;
import com.stripe.stripeterminal.external.callable.Cancelable;
import com.stripe.stripeterminal.external.callable.ConnectionTokenCallback;
import com.stripe.stripeterminal.external.callable.ConnectionTokenProvider;
import com.stripe.stripeterminal.external.callable.DiscoveryListener;
import com.stripe.stripeterminal.external.callable.PaymentIntentCallback;
import com.stripe.stripeterminal.external.callable.ReaderCallback;
import com.stripe.stripeterminal.external.callable.TerminalListener;
import com.stripe.stripeterminal.external.models.BatteryStatus;
import com.stripe.stripeterminal.external.models.CollectConfiguration;
import com.stripe.stripeterminal.external.models.ConnectionConfiguration;
import com.stripe.stripeterminal.external.models.ConnectionStatus;
import com.stripe.stripeterminal.external.models.DiscoveryConfiguration;
import com.stripe.stripeterminal.external.models.DiscoveryMethod;
import com.stripe.stripeterminal.external.models.PaymentIntent;
import com.stripe.stripeterminal.external.models.PaymentStatus;
import com.stripe.stripeterminal.external.models.Reader;
import com.stripe.stripeterminal.external.models.ReaderEvent;
import com.stripe.stripeterminal.external.models.TerminalException;
import com.stripe.stripeterminal.log.LogLevel;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;

/**
 * StripeConnectionPlugin
 */
public class StripeConnectionPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.RequestPermissionsResultListener {
    private MethodChannel channel;

    private Activity currentActivity = new Activity();

    private Cancelable discoveryTask;


    private List<String> permissions;

    private Integer REQUEST_CODE_LOCATION = 1012;
    /**stripe localId*/
    private String localId;
    /**现金钱箱号码*/
    private String cashBoxNum;

    /**M2sn号*/
    private String sn;
    /**获取stripeToken服务器Url*/
    private String baseUrl;

    /**发送至服务器错误日志Url*/
    private String errorUrl;

    private PaymentIntent paymentIntent;

    private Cancelable collectPaymentMethod;

    private BluetoothAdapter adapter;

    private BleDevice curBleDevice;





    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {

            case "permissionAllowed":
                _isPermissionAllowed();

                break;
            case "init":
                this.localId = call.argument("localId");
                this.sn = call.argument("sn");
                this.baseUrl = call.argument("baseUrl");
                this.errorUrl = call.argument("errorUrl");
                if (_isPermissionAllowed()) {
                    init();
                }
                break;

            case "cashBox":
                this.cashBoxNum =call.argument("cashBoxNum");
                if(cashBoxNum!=null&&!cashBoxNum.equals("")){

                    BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                            .setDeviceName(false, cashBoxNum)
                            .setScanTimeOut(10000)
                            .build();
                    BleManager.getInstance().initScanRule(scanRuleConfig);
                    scanCashBox();
                }

                break;

            case "openCash":
                openCash(result);
                break;

            case "disconnectReader":
                if (Terminal.getInstance().getConnectedReader() != null) {
                    Terminal.getInstance().disconnectReader(new Callback() {
                        @Override
                        public void onSuccess() {
                            System.out.println("断开");
                        }

                        @Override
                        public void onFailure(@NotNull TerminalException e) {
                        }
                    });
                }
                break;

            case "retrievePaymentIntent":
                retrievePaymentIntent(call, result);
                break;
            case "cancelRetrievePaymentIntent":
                cancelRetrievePaymentIntent(result);
                break;
            case "processPayment":
                processPayment(result);
                break;
            case "cancelProcessPayment":
                cancelProcessPayment(result);
                break;
            default:
                result.notImplemented();
        }
    }


    private  void  scanCashBox(){
        BleManager.getInstance().scanAndConnect(new BleScanAndConnectCallback() {
            @Override
            public void onScanStarted(boolean success) {

            }

            @Override
            public void onScanning(BleDevice bleDevice) {

            }

             @Override
            public void onScanFinished(BleDevice scanResult) {

            }

            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {

            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        channel.invokeMethod("onCashBoxConnectionChange", true);
                    }
                });
                curBleDevice = bleDevice;
                BleManager.getInstance().cancelScan();

            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        channel.invokeMethod("onCashBoxConnectionChange", false);
                    }
                });
                curBleDevice = null;
                if (BleManager.getInstance().isConnected(device)) {
                    BleManager.getInstance().disconnect(device);
                }

            }
        });
    }


    private Boolean _isPermissionAllowed() {
        List<Integer> permissionStatus = new ArrayList<>();
        List<Boolean> cannotAskPermissions = new ArrayList<>();
        for (String item : permissions) {
            permissionStatus.add(ContextCompat.checkSelfPermission(currentActivity, item));
            cannotAskPermissions.add(ActivityCompat.shouldShowRequestPermissionRationale(currentActivity, item));
        }
        final BluetoothManager bluetoothManager =(BluetoothManager) currentActivity.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
        adapter  = bluetoothManager != null ? bluetoothManager.getAdapter() : null;
        if (!adapter.isEnabled()) {
            adapter.enable();
        }
       BleManager.getInstance().init(currentActivity.getApplication());
        BleManager.getInstance().setSplitWriteNum(20);
        if (!permissionStatus.contains(PackageManager.PERMISSION_DENIED)) {

            return true;
        }
        if (cannotAskPermissions.contains(true)) {
            return false;
        }
        ActivityCompat.requestPermissions(currentActivity,
                (String[]) permissions.toArray(),
                REQUEST_CODE_LOCATION);
        final LocationManager locationManager =
                (LocationManager) currentActivity.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        boolean gpsEnabled = false;
        try {
            gpsEnabled = locationManager != null &&
                    locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception exception) {
        }
        return gpsEnabled;
    }

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {

        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "stripe_connection_plugin");
        channel.setMethodCallHandler(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            String[] array = {Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.READ_PHONE_STATE
                    };
            permissions = Arrays.asList(array);
        } else {
            String[] array = {Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                   };
            permissions = Arrays.asList(array);
        }


    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }



    private void disconnectReader(){
        if (Terminal.getInstance().getConnectedReader() != null) {
            Terminal.getInstance().disconnectReader(new Callback() {
                @Override
                public void onSuccess() {
                    System.out.println("断开");
                }

                @Override
                public void onFailure(@NotNull TerminalException e) {
                }
            });
        }
    }

    public  void openCash( Result result ){
        if(curBleDevice!=null){
            List<BluetoothGattService> bluetoothGattServices = BleManager.getInstance().getBluetoothGattServices(curBleDevice);
            for (BluetoothGattService service:bluetoothGattServices) {
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic:characteristics) {
                    if(characteristic.getProperties()==BluetoothGattCharacteristic.PROPERTY_WRITE){
                        BleManager.getInstance().write(
                                curBleDevice,
                                service.getUuid().toString(),
                                characteristic.getUuid().toString(),
                                HexUtil.hexStringToBytes("7a6869696f74"),
                                new BleWriteCallback() {
                                    @Override
                                    public void onWriteSuccess(int current, int total, byte[] justWrite){
                                        System.out.println("成功");
                                    }

                                    @Override
                                    public void onWriteFailure(BleException exception) {

                                    }
                                });
                    }
                }

            }
        }

    }


    /***
     *
     * 初始化
     * */
    private void init() {
        try {
            Terminal.initTerminal(currentActivity.getApplicationContext(), LogLevel.VERBOSE, new ConnectionTokenProvider() {
                        @Override
                        public void fetchConnectionToken(@NonNull ConnectionTokenCallback connectionTokenCallback) {
                            HttpURLConnection connection = null;
                            try {
                                URL url = new URL(baseUrl);

                                connection = (HttpURLConnection) url.openConnection();
                                //GET请求
                                connection.setRequestMethod("POST");


                                //获取数据成功
                                if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                                    //服务器响应返回的字节流
                                    InputStream inputStream = connection.getInputStream();
                                    //转换成字符流
                                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

                                    StringBuilder response = new StringBuilder();
                                    String line = "";
                                    while ((line = bufferedReader.readLine()) != null) {
                                        response.append(line);
                                    }

                                    //关闭io流
                                    inputStream.close();
                                    bufferedReader.close();
                                    connectionTokenCallback.onSuccess(stringToMap(response.toString()).get("secret"));
                                }
                            } catch ( Exception e) {
                                currentActivity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        channel.invokeMethod("onErrorLog", "fetchConnectionToken()"+e.getMessage());
                                    }
                                });
                                sendErrorLog("fetchConnectionToken()"+e.getMessage());
                            } finally {
                                if (null != connection) {
                                    connection.disconnect();
                                }
                            }
                        }
                    },
                    new TerminalListener() {
                        @Override
                        public void onUnexpectedReaderDisconnect(@NotNull Reader reader) {
                            discoverReadersStart();

                        }

                        @Override
                        public void onConnectionStatusChange(@NotNull ConnectionStatus status) {
                            Log.i("ConnectionStatusChange", status.toString());
                            currentActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    channel.invokeMethod("onStatusChange", status.toString());
                                }
                            });
                        }

                        @Override
                        public void onPaymentStatusChange(@NotNull PaymentStatus status) {
                            Log.i("PaymentStatusChange", status.toString());
                        }
                    });
            discoverReadersStart();
        } catch (TerminalException e) {
            currentActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    channel.invokeMethod("onErrorLog","initTerminal()"+ e.getMessage());
                }
            });
            sendErrorLog("initTerminal()"+ e.getMessage());
            throw new RuntimeException("Location services are required in order to initialize " +
                    "the Terminal.", e);
        }


    }

    /**
     * 连接
     */
    private void connection(Reader connectionReader) {

        ReaderCallback readerCallback = new ReaderCallback() {
            @Override
            public void onSuccess(@NotNull Reader reader) {
                discoverReadersStop();
            }

            @Override
            public void onFailure(@NotNull TerminalException e) {
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        channel.invokeMethod("onErrorLog", "readerCallback()"+e.getErrorMessage());
                    }
                });
                sendErrorLog("readerCallback()"+e.getErrorMessage());

            }
        };
        if (localId != null && !localId.equals("")) {
            Terminal.getInstance().connectBluetoothReader(connectionReader, new ConnectionConfiguration.BluetoothConnectionConfiguration(localId),
                    new BluetoothReaderListener() {
                        @Override
                        public void onReportReaderEvent(@NonNull ReaderEvent event) {
                            BluetoothReaderListener.super.onReportReaderEvent(event);

                            currentActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    channel.invokeMethod("onInsert", event.toString());
                                }
                            });
                        }

                        @Override
                        public void onBatteryLevelUpdate(float batteryLevel, @NonNull BatteryStatus batteryStatus, boolean isCharging) {
                            BluetoothReaderListener.super.onBatteryLevelUpdate(batteryLevel, batteryStatus, isCharging);
                            currentActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    channel.invokeMethod("onBatteryLevel", batteryLevel);
                                }
                            });
                        }
                        @Override
                        public void onReportLowBatteryWarning(){
                            disconnectReader();
                            connection(connectionReader);
                            currentActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    channel.invokeMethod("onBatteryWarning", "电量不足警告,请及时充电");
                                }
                            });
                        }
                    }, readerCallback);
        }

    }

    /**
     * 扫描stripe设备
     */
    private void discoverReadersStart() {
        final DiscoveryConfiguration config = new DiscoveryConfiguration(
                20, DiscoveryMethod.BLUETOOTH_SCAN, false);
        discoveryTask = Terminal
                .getInstance()
                .discoverReaders(config, new DiscoveryListener() {
                    @Override
                    public void onUpdateDiscoveredReaders(@NonNull List<Reader> list) {
                        if (sn != null && !sn.equals("")) {
                            Reader connectionReader = null;
                            for (Reader item : list) {
                                if (item.getSerialNumber().equals(sn)) {
                                    connectionReader = item;
                                    break;
                                }
                            }
                            if (connectionReader != null) {
                                connection(connectionReader);
                            }
                        }
                    }
                }, new Callback() {
                    @Override
                    public void onSuccess() {
//                    viewModel.discoveryTask = null;
                    }

                    @Override
                    public void onFailure(@NotNull TerminalException e) {
                        currentActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                channel.invokeMethod("onErrorLog", "discoverReadersStart"+e.getErrorMessage());
                            }
                        });
                        sendErrorLog("discoverReadersStart()"+e.getErrorMessage());

                        discoverReadersStart();
                    }
                });
    }

    /**
     * 关闭扫描stripe设备
     */
    private void discoverReadersStop() {
        if (discoveryTask != null) {
            discoveryTask.cancel(new Callback() {
                @Override
                public void onSuccess() {

                    discoveryTask = null;

                }

                @Override
                public void onFailure(@NotNull TerminalException e) {
                    discoveryTask = null;
                }
            });
        }
    }

    /**
     * 检索刷卡状态
     */
    private void retrievePaymentIntent(MethodCall call, Result result) {

        if (Terminal.getInstance().getConnectedReader() == null) {
            result.error(
                    "stripeTerminal#deviceNotConnected",
                    "You must connect to a device before you can use it.",
                    null
            );

        } else {

            String paymentIntentClientSecret = call.argument("paymentIntentClientSecret");
            if (paymentIntentClientSecret == null) {
                result.error(
                        "stripeTerminal#invalidPaymentIntentClientSecret",
                        "The payment intent client_secret seems to be invalid or missing.",
                        null
                );
                return;
            }

            Map<String, Object> collectConfiguration = call.argument("collectConfiguration");
            CollectConfiguration collectConfig = new CollectConfiguration.Builder().skipTipping(
                    (Boolean) collectConfiguration.get("skipTipping")).build();
            Terminal.getInstance()
                    .retrievePaymentIntent(
                            paymentIntentClientSecret,
                            new PaymentIntentCallback() {
                                @Override
                                public void onSuccess(@NonNull PaymentIntent intent) {
                                    paymentIntent = intent;

                                    collectPaymentMethod = Terminal.getInstance().collectPaymentMethod(
                                            paymentIntent,
                                            new PaymentIntentCallback() {
                                                @Override
                                                public void onSuccess(@NonNull PaymentIntent intent1) {
                                                    paymentIntent = intent1;
                                                    Gson gson = new Gson();
                                                    result.success(gson.fromJson(gson.toJson(paymentIntent),new TypeToken<Map<String, Object>>(){}.getType()));
                                                }

                                                @Override
                                                public void onFailure(@NonNull TerminalException e) {
                                                    result.error(
                                                            "stripeTerminal#unableToCollectPaymentMethod",
                                                            "Stripe reader was not able to collect the payment method for the provided payment intent. ${e.errorMessage}",
                                                            e.getErrorMessage()
                                                    );
                                                    sendErrorLog("collectPaymentMethod()"+e.getErrorMessage());
                                                }
                                            }, collectConfig

                                    );
                                }

                                @Override
                                public void onFailure(@NonNull TerminalException e) {
                                    result.error(
                                            "stripeTerminal#unableToRetrivePaymentIntent",
                                            "Stripe was not able to fetch the payment intent with the provided client secret. ${e.errorMessage}",
                                            e.getErrorMessage()
                                    );
                                    sendErrorLog("retrievePaymentIntent()"+e.getErrorMessage());
                                }
                            }
                    );
        }
    }

    /**
     * 取消检索刷卡状态
     */
    private void cancelRetrievePaymentIntent(Result result) {
        if (collectPaymentMethod == null) {
            result.error(
                    "stripeTerminal#unabelToCancelDiscover",
                    "There is no discover action running to stop.",
                    null
            );
        } else {
            collectPaymentMethod.cancel(new Callback() {
                @Override
                public void onFailure(@NonNull TerminalException e) {
                    result.error(
                            "stripeTerminal#unabelToCancelDiscover",
                            "Unable to stop the discover action because ${e.errorMessage}",
                            e.getErrorMessage()
                    );
                    sendErrorLog("cancelRetrievePaymentIntent()"+e.getErrorMessage());
                }

                @Override
                public void onSuccess() {
                    result.success(true);
                }
            });
            collectPaymentMethod = null;

        }
    }

    /**
     * 处理付款
     */
    private void processPayment(Result result) {
        if (paymentIntent == null) {
            result.error(
                    "stripeTerminal#unableToProcessPayment",
                    "Stripe reader was not able to process the payment for the provided payment intent",
                    null
            );
            return;
        }
        Terminal.getInstance()
                .processPayment(
                        paymentIntent,
                        new PaymentIntentCallback() {
                            @Override
                            public void onSuccess(PaymentIntent intent) {

                                paymentIntent = null;
                                Gson gson = new Gson();
                                result.success(gson.fromJson(gson.toJson(intent),new TypeToken<Map<String, Object>>(){}.getType()));
                            }

                            @Override
                            public void onFailure(TerminalException e) {
                                paymentIntent = null;
                                result.error(
                                        "stripeTerminal#unableToProcessPayment",
                                        "Stripe reader was not able to process the payment for the provided payment intent. ${e.errorMessage}",
                                        e.getErrorMessage()
                                );
                                sendErrorLog("processPayment()"+e.getErrorMessage());
                            }
                        });
    }

    /**
     * 取消付款意向
     */
    private void cancelProcessPayment(Result result) {
        if (paymentIntent == null) {
            result.error(
                    "stripeTerminal#unableToProcessPayment",
                    "Stripe reader was not able to process the payment for the provided payment intent",
                    null
            );
            return;
        }
        Terminal.getInstance()
                .cancelPaymentIntent(
                        paymentIntent,
                        new PaymentIntentCallback() {
                            @Override
                            public void onSuccess(PaymentIntent intent) {

                                paymentIntent = null;
                                Gson gson = new Gson();
                                result.success(gson.fromJson(gson.toJson(intent),new TypeToken<Map<String, Object>>(){}.getType()));
                            }

                            @Override
                            public void onFailure(TerminalException e) {
                                paymentIntent = null;
                                result.error(
                                        "stripeTerminal#unableToProcessPayment",
                                        "Stripe reader was not able to process the payment for the provided payment intent. ${e.errorMessage}",
                                        e.getErrorMessage()
                                );
                                sendErrorLog("cancelProcessPayment()"+e.getErrorMessage());
                            }
                        });
    }


    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
        currentActivity = activityPluginBinding.getActivity();
        activityPluginBinding.addRequestPermissionsResultListener(this);
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        currentActivity = null;
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding activityPluginBinding) {
        currentActivity = activityPluginBinding.getActivity();

    }

    @Override
    public void onDetachedFromActivity() {
        currentActivity = null;
    }


    @Override
    public boolean onRequestPermissionsResult(int i, @NonNull String[] strings, @NonNull int[] ints) {
        List<Integer> permissionStatus = new ArrayList<>();
        for (String item : permissions) {
            permissionStatus.add(ContextCompat.checkSelfPermission(currentActivity, item));
        }
        if (!permissionStatus.contains(PackageManager.PERMISSION_DENIED)) {
//            init();


        }
        return i == REQUEST_CODE_LOCATION;
    }

    private   Map<String, String> stringToMap(String param) {
        Map<String, String> map = new HashMap<>();


        //去除{}
        String s1 = param.replace("{", "");
        String s2 = s1.replace("}", "");
        String s3 = s2.trim();


        //1.根据逗号分隔
        String[] split = s3.split(",");

        for (int i = split.length - 1; i >= 0; i--) {

            String trim = split[i].trim();
            String[] split1 = trim.split(":");

            map.put(split1[0].replace("\"",""),split1[1].replace("\"",""));

        }

        return map;
    }


    public  void sendErrorLog(String log){
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL(errorUrl);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setRequestMethod("POST");	//需要声明POST
                    OutputStream os = connection.getOutputStream();
                    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                    BufferedWriter bw = new BufferedWriter(osw);
                    bw.write("strLog="+log);
                    bw.flush();
                    //获取数据成功
                    if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                        //服务器响应返回的字节流
                        InputStream inputStream = connection.getInputStream();
                        //转换成字符流
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

                        StringBuilder response = new StringBuilder();
                        String line = "";
                        while ((line = bufferedReader.readLine()) != null) {
                            response.append(line);
                        }

                        //关闭io流
                        inputStream.close();
                        bufferedReader.close();

                    }

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }.start();

    }
}
